// 实现一个单向链表结构

class Update {
  constructor(payload, nextUpdate) {
    this.payload = payload;
    this.nextUpdate = nextUpdate;
  }
}

class UpdateQueue {
  constructor() {
    this.baseState = null;
    this.firstUpdate = null;
    this.lastUpdate = null;
  }

  enqueueUpdate(update) {
    // 构建单向链表
    if (!this.firstUpdate) {
      this.firstUpdate = this.lastUpdate = update;
    } else {
      this.lastUpdate.nextUpdate = update;
      this.lastUpdate = update;
    }
  }

  forceUpdate() {
    // 进行更新操作
    let currentState = this.baseState || {};
    let currentUpdate = this.firstUpdate;
    while (currentUpdate) {
      let state =
        currentUpdate.payload instanceof Function
          ? currentUpdate.payload(currentState)
          : currentUpdate.payload;
      currentState = { ...currentState, ...state };
      currentUpdate = currentUpdate.nextUpdate;
    }
    this.baseState = currentState;
    this.firstUpdate = this.lastUpdate = null;
    return currentState;
  }
}

const queue = new UpdateQueue();
queue.enqueueUpdate(new Update({ name: '张三' }));
queue.enqueueUpdate(new Update({ number: 0 }));
queue.enqueueUpdate(new Update((state) => ({ number: state.number + 1 })));
queue.enqueueUpdate(new Update((state) => ({ number: state.number + 1 })));
queue.forceUpdate();
console.log(queue.baseState);
